<?php

namespace App\Api\Controllers;

use App\Api\Validate\ComplaintsValidate;
use App\Api\Validate\MiniUserValidate;
use App\Models\RoomSendEva;
use App\Models\RoomSendHis;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class ComplaintsController extends BaseController
{

    public function index(Request $request)
    {
        $pageNum  = $request->get("page_num");
        $pageSize = $request->get("page_size",20);

        $columns = ['id', 'images', 'content', 'score', 'created_at'];
        $where = [
            ['openid', $this->user->openid],
            ['status', 1]
        ];
        $model = RoomSendEva::where($where)
            ->orderBy("id", "desc")
            ->paginate($pageSize, $columns, "page", $pageNum);
        $list = $model->getCollection();
        foreach ($list as $item) {
            $item->images = json_decode($item->images, true);
        }
        return Success(10100, [
            "data" => $list,
            "page_info" => [
                'current' => $model->currentPage(), 'page_size' => (int)$pageSize, "count" => $model->total(),
                "pages"   => $model->lastPage()
            ]
        ]);
    }


    public function detail(Request $request)
    {
        $id = $request->get("id");

        // 评价信息
        $record = (new ComplaintsValidate())->detail($id);

        // 送物信息
        $list = DB::table('room_send_his')
            ->leftJoin('goods', 'room_send_his.goods_id', '=', 'goods.id')
            ->where('room_send_his.rse_id', $id)
            ->select('room_send_his.id','room_send_his.num','room_send_his.created_at','room_send_his.goods_id','goods.name','goods.image')
            ->get();

        $record->images = json_decode($record->images, true);
        $record->list = $list;
        return Success(10100, $record);
    }

    public function add(Request $request)
    {
        $params = $request->all();
        $params['openid'] = $this->user->openid;

        (new \App\Api\Validate\ComplaintsValidate())->add($params);

        $living = (new MiniUserValidate())->checkLiving($this->user->openid);

        // 送物订单验证
        $historyIds = (new ComplaintsValidate())->checkRoomSendHis($params, $living);


        DB::beginTransaction();
        // 添加评价记录
        $complaint = (new RoomSendEva())->add($params);
        if (!$complaint) {
            return $this->fail(402, '评论失败，请稍后重试');
        }

        // 添加评论关联
        $result = RoomSendHis::whereIn('id', $historyIds)->update(['rse_id' => $complaint->id]);
        if (!$result) {
            DB::rollBack();
            return $this->fail(402, '添加评论关联失败，请稍后重试');
        }

        DB::commit();

        //TODO 是否发送模板消息

        return $this->success(200, '感谢您的支持');
    }
}
